package test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class CurrencyClass {
	
	private static final String DATE_VALIDATION_PATTERN = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
	private static String nazwa;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(getCurrencyValue("06/06/2013", "THB"));
		System.out.println(getCurrencyValue("32/07/2013", "THB"));
		System.out.println(getCurrencyValue("06/07/2014", "USD"));
		System.out.println(getCurrencyValue("06/06/2013", "EUR"));
		System.out.println(getCurrencyValue("13/07/2014", "EUR"));
		System.out.println(getCurrencyValue("06/06/2014", "ABC"));
	}
	
	public static String getCurrencyValue(String date, String scut){
		String info = "";
		try{
			
			Pattern firstPatt = Pattern.compile(DATE_VALIDATION_PATTERN);
			Matcher firstMatch = firstPatt.matcher(date);
			boolean gotIt = firstMatch.matches() ? true : false;
			if(!gotIt)
				info = "Niepoprawny format daty!";
			else{
				String correctDate = date.substring(6, 10)+"-"+date.substring(3, 5)+"-"+date.substring(0, 2);
				URL link = new URL("http://www.nbp.pl/kursy/xml/dir.aspx?tt=A");
				BufferedReader in = null;
				URLConnection conn = null;
				conn = link.openConnection();
				conn.connect();
				in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				//System.out.println(correctDate+" -- "+correctDate.length());
				String inputline ="";
				boolean find = false;
				while ((inputline = in.readLine()) != null) {
					//System.out.println(inputline);
					Pattern patern = Pattern.compile(correctDate);
					Matcher matchdata = patern.matcher(inputline);
					find = matchdata.find();
					//System.out.println("/kursy/xml/"+inputline);
					if (find) {
						nazwa = "/kursy/xml/"+inputline.substring(38, 53);
						break;
					}
				}
				if(find) info = getFinalValue(nazwa, scut);
				else info = "Brak kursow z tego dnia!";	
		   }	
		}
		
		catch(Exception ex){
			System.out.println(ex);
		}
		return info;
	}
	
	public static String getFinalValue(String nameOfCurr, String scOfCurr){
        String dibsVal = "";
		try{
			URL url = new URL("http://www.nbp.pl"+nameOfCurr);
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(url.openStream());
            String dibsCode = "";
            NodeList nLista = doc.getElementsByTagName("pozycja");
            String selectedDibs = scOfCurr;
            
            for(int i=0; i<nLista.getLength(); i++){
                Node nNode = nLista.item(i);
                if(nNode.getNodeType() == Node.ELEMENT_NODE){
                    Element elem = (Element)nNode; 
                    dibsCode = elem.getElementsByTagName("kod_waluty").item(0).getTextContent();
                    if(dibsCode.equals(selectedDibs)){
                    	dibsVal = elem.getElementsByTagName("kurs_sredni").item(0).getTextContent();
                    	break;
                    }
                    else dibsVal = "Nie ma waluty o takim skrocie!";
                }
            }
		}
		
		catch(Exception ex){
			System.out.println(ex);
		}
		return dibsVal;
	}

}
